package com.warf.warftool;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.tanukisoftware.wrapper.WrapperListener;
import org.tanukisoftware.wrapper.WrapperManager;

import com.warf.warftool.utils.WarfUtils;
import com.warf.warftool.was.WasConfigApp;

public class WarfConfExecutionMain implements WrapperListener {
	private static Properties warfProperties;
	private static String WARF_CONF_PROPS_FILE="WarfConfigApp.conf";
	private static String WARF_CONF_ROOT="warfConfig.";
	@Override
	public void controlEvent(int event) {
		// TODO Auto-generated method stub
	 if ( ( event == WrapperManager.WRAPPER_CTRL_LOGOFF_EVENT )
                && ( WrapperManager.isLaunchedAsService() || WrapperManager.isIgnoreUserLogoffs() ) )
        {
                // Ignore
        }
        else
        {
                WrapperManager.stop( 0 );
                // Will not get here.
        }
	}
	
	

	@Override
	public Integer start(String[] arg0) {
		// TODO Auto-generated method stub
	
		CommandLineParser parser= new DefaultParser();
		Options options=createOptions();
		String appName="";
		String dmgrName="";
		String dmgrhost="";
		String dmgrport="";
		String dmgruser="";
		String dmgrpass="";
		String scriptpath="";
		String configaction="";
		String configtask="";
		String webappsDir="";
		try{
			CommandLine line= parser.parse(options, arg0);
			if(arg0.length < 1){
				showHelp(options);
				return -1;
			}
			if(line.hasOption("h") || line.hasOption("help")){
				showHelp(options);
				return null;
			}
			
			String[] argList=line.getArgs();
			if(argList.length < 1){
				System.out.println("AppName is Undefined");
				showHelp(options);
				return -1;
			}else{
				appName=argList[0];
			}
			
			System.out.println("Application Name: "+appName);
			System.out.println("Loading Properties File");
			loadProperties();
			System.out.println("OK");
			
			
			if(line.hasOption('n')){
				System.out.println("Dmgr Name specified");
				
				if(line.getOptionValue("n") != null){
					dmgrName=line.getOptionValue("n");	
					System.out.println("Dmgr Name: "+dmgrName);
				}
			}
			
			if(line.hasOption('a')){
				configaction=line.getOptionValue('a');
				if(configaction.equalsIgnoreCase("")){
					configaction=line.getOptionValue("a");
				}
			}
			
			if(line.hasOption('t') ){
				configtask=line.getOptionValue('t');
				if(configtask.equalsIgnoreCase("")){
					configtask=line.getOptionValue("t");
				}
			}
			
			if(!dmgrName.equalsIgnoreCase("")){
				System.out.println("Load DMGR info from property file :"+dmgrName );
				dmgrhost=getPropertyBaseRoot(dmgrName,"dmgr.hostname");
				dmgrport=getPropertyBaseRoot(dmgrName,"dmgr.port");
				dmgruser=getPropertyBaseRoot(dmgrName,"dmgr.username");
				dmgrpass=getPropertyBaseRoot(dmgrName,"dmgr.password"); 
				webappsDir=getPropertyBaseRoot(dmgrName,"dmgr.webapps.dir");
			}else{
				if(line.hasOption("host")){
					dmgrhost=line.getOptionValue("host");
				}
				if(line.hasOption("port")){
					dmgrport=line.getOptionValue("port");
				}
				if(line.hasOption("user")){
					dmgruser=line.getOptionValue("user");
				}
				if(line.hasOption("password")){
					dmgrpass=line.getOptionValue("password");
				}
				
				webappsDir=getPropertyValue(WARF_CONF_ROOT+"base.dmgr.webapps.dir");
			}
			System.out.println("Reading Script Path");
			scriptpath=getPropertyValue(WARF_CONF_ROOT+"root.scripts.path");
			if(scriptpath == null ){
				System.out.println("Script Path is missing in: "+WARF_CONF_PROPS_FILE);
				return -1;
			}
			if(webappsDir == null){
				System.out.println("Web Apps Dir Path is missing in: "+WARF_CONF_PROPS_FILE);
				return -1;
			}
			
			System.out.println("OK");
			
			if(dmgrhost == null || dmgrport == null || dmgruser == null || dmgrpass == null ){
				System.out.println("Dmgr information is missing");
				showHelp(options);
				return -1;
			}
			
			
			if(dmgrhost.equalsIgnoreCase("")||
					dmgrport.equalsIgnoreCase("") ||
					dmgruser.equalsIgnoreCase("") ||
					dmgrpass.equalsIgnoreCase("")){
				System.out.println("Dmgr information is missing");
				showHelp(options);
				return -1;
			}else{
				WasConfigApp wasConfigApp= new WasConfigApp(appName); 
				wasConfigApp.setScriptPath(scriptpath);
				wasConfigApp.setRootFolder(scriptpath+"/WAS");
				wasConfigApp.setWebappsDir(webappsDir);
				wasConfigApp.setDmgrHostName(dmgrhost);
				wasConfigApp.setDmgrPortName(dmgrport);
				wasConfigApp.setDmgrUsername(dmgruser);
				wasConfigApp.setDmgrPassword(dmgrpass);
				wasConfigApp.run();
				return null;
			}
			
					
		}catch( ParseException exp){
				showHelp(options);
		}
			
		
		return null;
	}

	@Override
	public int stop(int arg0) {
		// TODO Auto-generated method stub
		return arg0;
	}
	public static void showHelp(Options options){
		HelpFormatter formatter = new HelpFormatter();
		formatter.printHelp("WARFConfigApp [OPTIONS] [AppName]", options);
	}
	public static Options createOptions(){
		Options options = new Options();
		options.addOption("h", "help", false, "Print this Message");
		options.addOption("a", "action", false, "Action to perform. NEW/UPDATE/REMOVE");
		options.addOption("t", "task", false, "Tasks List");
		options.addOption("n", "name", true, "WARF Dmgr Name");
		options.addOption("host", true, "Dmgr host Name");
		options.addOption("port", true, "Dmgr SOAP Port");
		options.addOption("user", true, "Dmgr Security Username");
		options.addOption("password", true, "Dmgr Security Password");
		return options;
	}
	public void loadProperties(){
		try {
			warfProperties = new Properties();
			warfProperties.load(WarfConfExecutionMain.class.getClassLoader().getResourceAsStream(WARF_CONF_PROPS_FILE));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			warfProperties= null;
			e.printStackTrace();
		} catch (IOException e) {
			warfProperties= null;
			e.printStackTrace();

		}
	}
	public static String getPropertyValue(String key){
		if(warfProperties != null){
			String tempString=warfProperties.getProperty(key);
			return tempString;
		}
		return "";
	}
	public static String getPropertyBaseRoot(String appName, String key){
	//	System.out.println("name: "+appName+ " Key: "+key);
		String levelValue=getPropertyValue(WARF_CONF_ROOT+appName+"."+key);
		if(levelValue == null){
			levelValue=getPropertyValue(WARF_CONF_ROOT+"base."+key);
		}
		return levelValue;
	}
	public static void main( String[] args ){
		
		WrapperManager.start( new WarfConfExecutionMain(), args );

	 }

}
